const fs = require("fs");
const axios = require("axios");
const https = require("https");
const { loadConfig } = require("./config");

// 读取配置文件
const config = loadConfig();
const pexelsApiKey = config.pexelsApiKey;

// 创建忽略SSL证书错误的HTTPS代理
const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
});
const MAX_SIZE = 1024 * 1024 * 10;
/**
 * 从Pexels下载资源的通用函数
 * @param {string} query - 搜索关键词
 * @param {string} outputPath - 输出文件路径
 * @param {string} resourceType - 资源类型 ('image' 或 'video')
 * @param {number} minWidth - 最小宽度
 * @param {number} minHeight - 最小高度
 * @returns {boolean} 是否成功下载
 */
async function downloadFromPexels(query, outputPath, resourceType, minWidth = 1200, minHeight = 768) {
  try {
    console.log(`    正在搜索${resourceType === "video" ? "视频" : "图片"}关键词: ${query}`);

    let searchUrl;
    if (resourceType === "video") {
      // 搜索视频
      searchUrl = `https://api.pexels.com/videos/search?query=${encodeURIComponent(query)}&per_page=10`;
    } else {
      // 搜索图片，要求最小尺寸
      searchUrl = `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&per_page=10&size=medium`;
    }

    const searchResponse = await axios.get(searchUrl, {
      headers: {
        Authorization: pexelsApiKey,
      },
      httpsAgent,
    });

    // 处理资源搜索结果的通用逻辑
    let resources, resourceTypeName;
    if (resourceType === "video") {
      resources = searchResponse.data.videos.filter(video => video.width >= minWidth && video.height >= minHeight);
      resourceTypeName = "视频";
    } else {
      resources = searchResponse.data.photos.filter(photo => photo.width >= minWidth && photo.height >= minHeight);
      resourceTypeName = "图片";
    }

    if (resources.length === 0) {
      console.log(`    没有找到合适的${resourceTypeName}: ${query}`);
      return false;
    }

    console.log(`    找到${resourceTypeName}数量: ${resources.length}`);

    // 选择合适的资源，如果是视频则检查大小
    let resource;
    if (resourceType === "video") {
      // 尝试找到文件大小合适的视频
      for (let i = 0; i < resources.length; i++) {
        const video = resources[i];
        const videoFiles = video.video_files.filter(file => file.quality === "hd");
        if (videoFiles.length > 0) {
          // 获取文件大小
          const headResponse = await axios.head(videoFiles[0].link, { httpsAgent });
          const contentLength = headResponse.headers['content-length'];
          
          if (!contentLength || contentLength <= MAX_SIZE) {
            resource = video;
            break;
          } else {
            console.log(`    视频过大 (${(contentLength / (1024 * 1024)).toFixed(2)} MB > ${(MAX_SIZE / (1024 * 1024)).toFixed(2)} MB)，尝试下一个资源`);
          }
        }
      }
      
      // 如果没有找到大小合适的视频，则使用第一个
      if (!resource && resources.length > 0) {
        resource = resources[0];
        console.log(`    没有找到大小合适的视频，使用第一个资源`);
      }
    } else {
      // 图片直接使用第一个
      resource = resources[0];
    }

    if (!resource) {
      console.log(`    没有找到合适的${resourceTypeName}: ${query}`);
      return false;
    }

    const resourceId = resource.id;
    const resourceWidth = resource.width;
    const resourceHeight = resource.height;
    console.log(`    找到${resourceTypeName}: ${resourceId}, 尺寸: ${resourceWidth}x${resourceHeight}`);

    // 获取资源下载链接
    let resourceUrl;
    if (resourceType === "video") {
      // 获取最高质量的视频文件链接
      const videoFiles = resource.video_files.filter(file => file.quality === "hd");
      if (videoFiles.length === 0) {
        console.log(`    视频没有可用的高质量版本`);
        return false;
      }
      resourceUrl = videoFiles[0].link;
    } else {
      // 获取大尺寸图片链接
      resourceUrl = resource.src.large2x || resource.src.large || resource.src.original;
    }

    console.log(`    下载${resourceTypeName}: ${resourceUrl}`);

    // 下载资源的通用逻辑
    const writer = fs.createWriteStream(outputPath);
    const response = await axios({
      url: resourceUrl,
      method: "GET",
      responseType: "stream",
      httpsAgent,
    });

    response.data.pipe(writer);

    return new Promise((resolve, reject) => {
      writer.on("finish", () => {
        console.log(`    ${resourceTypeName}下载完成: ${outputPath}`);
        resolve(true);
      });
      writer.on("error", err => {
        console.error(`！！！    ${resourceTypeName}下载失败:`, err.message);
        reject(false);
      });
    });
  } catch (error) {
    console.error(`！！！    Pexels ${resourceType === "video" ? "视频" : "图片"}下载错误:`, error.message);
    return false;
  }
}

module.exports = {
  downloadFromPexels,
  httpsAgent,
};